from pyecharts import options as opts
from pyecharts.charts import Pie, Timeline
from pyecharts.globals import ThemeType
import pandas as pd

def get_top15_manufacturer_pie_data(df):
    try:
        # 数据准备
        df_clean = df.copy()
        df_clean['销量'] = pd.to_numeric(df_clean['销量'], errors='coerce')
        df_clean = df_clean.dropna(subset=['年份', '月份', '厂商', '销量'])

        # 月销量统计
        monthly_sales = df_clean.groupby(['年份', '月份', '厂商'])['销量'].sum().reset_index()

        # 每月前15名
        def top_15_sales(sub_df):
            return sub_df.nlargest(15, '销量', keep='all')

        top_15_monthly = monthly_sales.groupby(['年份', '月份'], group_keys=False).apply(top_15_sales)

        # 构建时间轴图
        timeline = Timeline(init_opts=opts.InitOpts(theme=ThemeType.LIGHT))

        for (year, month), group in top_15_monthly.groupby(['年份', '月份']):
            pie = (
                Pie()
                .add(
                    "",
                    [list(z) for z in zip(group['厂商'], group['销量'])],
                    radius=["30%", "75%"]
                )
                .set_global_opts(
                    title_opts=opts.TitleOpts(title=f"{year}年{month}月销量前15厂商的销量占比"),
                    legend_opts=opts.LegendOpts(orient="vertical", pos_top="15%", pos_left="2%"),
                    toolbox_opts=opts.ToolboxOpts(is_show=True)
                )
                .set_series_opts(
                    label_opts=opts.LabelOpts(formatter="{b}: {c} ({d}%)")
                )
            )
            timeline.add(pie, time_point=f"{year}-{str(month).zfill(2)}")

        # 时间轴配置
        timeline.add_schema(
            play_interval=1000,
            is_auto_play=True,
            is_loop_play=True,
            is_timeline_show=True,
            label_opts=opts.LabelOpts(is_show=True)
        )

        return {
            'success': True,
            'chart_data': timeline.dump_options_with_quotes()
        }

    except Exception as e:
        return {
            'success': False,
            'error': f'处理数据出错: {str(e)}'
        }
